package com.yabushan.web.controller.data;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.yabushan.common.utils.StringUtils;
import io.swagger.annotations.Api;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.omg.CORBA.PRIVATE_MEMBER;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author yabushan
 * @memo 数据中台请求服务
 * @Date 2021/3/28 18:36
 * @Version 1.0
 */
@RestController
@Api(tags = "数据中台请求服务接口")
public class DataController {


    @Value("${daas.url}")
    private String url;
    @Value("${daas.accessKeyId}")
    private String accessKeyId;
    @Value("${daas.secertKey}")
    private String secertKey;
    @Value("${daas.projectId}")
    private String projectId;

    @PostMapping(value = "/data/getMessageRow")
    public String getMessageRow(String ApiCode, String param) {
        if(StringUtils.isEmpty(ApiCode)){
            return "服务编码不能为空!";
        }
        if(StringUtils.isEmpty(param)){
            return "请求参数不能为空";
        }
        String reslt = result(param, ApiCode,"row");
        JSONObject jsonObject = JSON.parseObject(reslt);
        String resultCode = jsonObject.getString("resultCode");
        String resultDesc = jsonObject.getString("resultDesc");
        String exception = jsonObject.getString("exception");
        String columnNames = jsonObject.getString("columnNames");
        String rows = jsonObject.getString("rows");
        ResultUtil resultUtil = new ResultUtil();
        resultUtil.setException(exception);
        resultUtil.setColumnNames(columnNames);
        resultUtil.setResultCode(resultCode);
        resultUtil.setRows(rows);
        return toJson(resultUtil);
    }

    @PostMapping(value = "/data/getMessageList")
    public String getMessageList(String ApiCode, String param) {
        if(StringUtils.isEmpty(ApiCode)){
            return "服务编码不能为空!";
        }
        if(StringUtils.isEmpty(param)){
            return "请求参数不能为空";
        }
        String reslt = result(param, ApiCode,"list");
        JSONObject jsonObject = JSON.parseObject(reslt);
        String resultCode = jsonObject.getString("resultCode");
        String resultDesc = jsonObject.getString("resultDesc");
        String exception = jsonObject.getString("exception");
        String columnNames = jsonObject.getString("columnNames");
        String rows = jsonObject.getString("rows");
        ResultUtil resultUtil = new ResultUtil();
        resultUtil.setException(exception);
        resultUtil.setColumnNames(columnNames);
        resultUtil.setResultCode(resultCode);
        resultUtil.setRows(rows);
        return toJson(resultUtil);
    }


    public String result(String param, String apiCode,String rowType) {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String resourceApiCode = apiCode;//"test2_39"; //根据实际修改,也可以使用resourceId
            String urlPath = url + resourceApiCode;
            HttpPost httpPost = new HttpPost(urlPath);
            httpPost.setHeader("X-Amz-Date", format.format(new Date()));
            StringBuffer stringBuffer = new StringBuffer();
            if("row".equals(rowType)){
                stringBuffer.append("{'sqlMode':'normal','rowType':'row','dataServiceParams':");
            }else{
                stringBuffer.append("{'sqlMode':'normal','rowType':'list','dataServiceParams':");
            }

            stringBuffer.append(param);
            stringBuffer.append("}");
            String requestBody = stringBuffer.toString();
            // String requestBody ="{'sqlMode':'normal','rowType':'list','dataServiceParams':{'rowId':'1'}}";
           // String accessKeyId = "4D65410461334A511EA0";
           // String secertKey = "upfXLphtOT7XlhrvxdnT4KrLKimmA4m667ZqXzdYe5QP2hMNsRuK341D"; //根据用户的 secertKey 修改
           // String projectId = "";
            // Bingoinsight：平台大数据平台英文名缩写，固定标识不可修改。
            // AccessKeyId：用户调用API所用的密钥ID。
            // secertKey:用户调用API所用的密钥ID 对应的秘钥。
            // ProjectId：用户可能管理多个项目，但是同一时间只能管理其中一个，传入项目ID；
            // Signature：使用AccessKey Secret对请求进行对称加密的签名。
            //  String param = "{'rowId':'1'}";
            //String requestBody = "{\"sqlMode\":\"normal\",\"rowType\":\"list\",\"dataServiceParams\":{\"rowId\":\"AAATSYAAFAAADakAAK\"}}";
            String signature = "Bingoinsight" + ":" + accessKeyId + ":" + projectId + ":" + HmacSHA1Signer.getSignString(requestBody, secertKey);
            httpPost.setHeader("Authorization", signature);
            RequestConfig config = RequestConfig.custom().setSocketTimeout(220000).setConnectTimeout(220000).build(); // 握手超时、连接超时配置
            httpPost.setConfig(config);
            httpPost.setEntity(new StringEntity(requestBody, "UTF-8"));
            CloseableHttpClient client = HttpClients.createDefault();
            CloseableHttpResponse response = client.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            String resultJSON = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            return resultJSON;
        } catch (Exception e) {
            return e.toString();
        }

    }


    public String toJson(Object obj) {
        Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd HH:mm:ss").serializeNulls().disableHtmlEscaping().create();
        String strReturn = gson.toJson(obj);
        return strReturn;
    }
}
